//
//  CTexture2D.cpp
//  OpenGLDemo
//
//  Created by 石超军 on 2018/7/6.
//  Copyright © 2018年 石超军. All rights reserved.
//

#include "CTexture2D.h"
#include <OpenGL/gl3.h>
#include "stb_image.h"
CTexture2D::CTexture2D(const char* path,CTEXTURE2D_INFO* info):m_textureId(0)
{
    LoadFromFile(path,info);
}
CTexture2D::~CTexture2D()
{
    glDeleteTextures(1, &m_textureId);
}

//从文件中加载
bool CTexture2D::LoadFromFile(const char* path,CTEXTURE2D_INFO* info)
{
    /* 纹理加载部分 */
    unsigned int &texture = m_textureId;
    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);
    // 为当前绑定的纹理对象设置环绕、过滤方式
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    
    stbi_set_flip_vertically_on_load(true);         //正向加载
    
    // 加载并生成纹理
    int width, height, nrChannels;
    unsigned char *data = stbi_load(path, &width, &height, &nrChannels, 0);
    if (data)
    {
        //判断颜色通道个数,决定不同的加载方式
        if(nrChannels == 3)
            glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
        else if(nrChannels == 4)
            glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
        else
            glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
        glGenerateMipmap(GL_TEXTURE_2D);
        
        if(info)
        {
            info->width = width;
            info->height = height;
            info->channels = nrChannels;
        }
    }
    else
    {
        std::cout << "Failed to load texture" << std::endl;
        glDeleteTextures(1, &texture);
        return false;
    }
    stbi_image_free(data);
    
    return true;
}
void CTexture2D::Active(unsigned int unit)
{
    glActiveTexture(unit);
    glBindTexture(GL_TEXTURE_2D, m_textureId);
}

unsigned int CTexture2D::GetId()
{
    return m_textureId;
}
